package com.wsc.wscbirthdaykeeper.widget;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.widget.RemoteViews;

import com.wsc.wscbirthdaykeeper.R;
import com.wsc.wscbirthdaykeeper.activities.PersonListActivity;
import com.wsc.wscbirthdaykeeper.managers.DatabaseManager;
import com.wsc.wscbirthdaykeeper.model.KRuntimeModel;
import com.wsc.wscbirthdaykeeper.model.entity.Person;
import com.wsc.wscbirthdaykeeper.persistence.dao.PersonDAO;
import com.wsc.wscbirthdaykeeper.utils.DialogUtils;
import com.wsc.wscbirthdaykeeper.utils.comparators.PersonComparator;

@SuppressLint({ "SimpleDateFormat", "Wakelock" })
public class WidgetProvider extends AppWidgetProvider {
	private KRuntimeModel runtime = KRuntimeModel.getInstance();

	@SuppressWarnings("deprecation")
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		try {

			// updateDB(context);
			for (int i = 0; i < appWidgetIds.length; i++) {
				Intent svcIntent = new Intent(context, WidgetService.class);

				svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
				svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));

				RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);
				widget.setRemoteAdapter(appWidgetIds[i], R.id.listView, svcIntent);

				Intent clickIntent = new Intent(context, PersonListActivity.class);
				PendingIntent clickPI = PendingIntent.getActivity(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				widget.setPendingIntentTemplate(R.id.listView, clickPI);

				appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
			}

			super.onUpdate(context, appWidgetManager, appWidgetIds);

		} catch (Exception e) {
			DialogUtils.showException(context, "WidgetProvider::onUpdate", e);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

		ComponentName thisAppWidget = new ComponentName(context.getPackageName(), WidgetProvider.class.getName());
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);
		appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listView);

		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
		wl.acquire();

		updateDB(context);

		boolean alarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context, WidgetProvider.class), PendingIntent.FLAG_NO_CREATE) != null);

		if (alarmUp) {
			// Toast.makeText(context, "Active", Toast.LENGTH_SHORT).show();
			// cancelAlarm(context);
		} else {
			// Toast.makeText(context, "DisActive", Toast.LENGTH_SHORT).show();
			setAlarm(context);
		}

		wl.release();
	}

	private void updateDB(Context ctxt) {
		try {
			DatabaseManager.getInstance().onCreationComplete();
			try {
				// Format formatter = new SimpleDateFormat("hh:mm:ss a");
				List<Person> persons = new ArrayList<Person>();
				persons.addAll(PersonDAO.queryForAll());
				// persons.add(new Person("" + formatter.format(new Date()), new
				// Date()));

				runtime.setPersons(persons);
				Collections.sort(runtime.getPersons(), new PersonComparator());
			} catch (SQLException e) {
				// Toast.makeText(ctxt, e.getMessage(),
				// Toast.LENGTH_SHORT).show();
				DialogUtils.showException(ctxt, e);
			}
		} catch (Exception e) {
			DialogUtils.showException(ctxt, "WidgetProvider::updateDB", e);
		}
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		cancelAlarm(context);
	}

	public void setAlarm(Context context) {
		Intent intent = new Intent(context, WidgetProvider.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 1);

		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pi);
	}

	public void cancelAlarm(Context context) {
		Intent intent = new Intent(context, WidgetProvider.class);
		PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}

	public void setOneTimeTimer(Context context) {
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, WidgetProvider.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10 * 1000, pi);
	}
}